import urllib2
import json

# Constants:
USE_TEST_DATA = True
DEBUG_PRINT = False

def get_wu_data():
    global conditions_parsed
    global forecast_parsed
    
    if USE_TEST_DATA:
        # Conditions Test Data
        with open('test_data/conditions') as data_file:
            conditions_parsed = json.load(data_file)
        # Forecast Test Data
        with open('test_data/forecast') as data_file:
            forecast_parsed = json.load(data_file)
    else:
        # This is the WeatherUnderground API key.  You need to register to get one.
        # Just put it in the wu_api.key file in the same folder as pi-weather.py
        f_apikey = open('wu_api.key')
        api_key = f_apikey.readline()
        f_apikey.close()        

        # Get Condistions
        conditions_url = urllib2.urlopen('http://api.wunderground.com/api/%s/conditions/q/OR/Hillsboro.json' % api_key)
        conditions_string = conditions_url.read()
        conditions_url.close()
        if DEBUG_PRINT: print conditions_string
        conditions_parsed = json.loads(conditions_string)

        # Get Forecast
        forecast_url = urllib2.urlopen('http://api.wunderground.com/api/%s/forecast/q/OR/Hillsboro.json' % api_key)
        forecast_string = forecast_url.read()
        forecast_url.close()
        if DEBUG_PRINT: print forecast_string
        forecast_parsed = json.loads(forecast_string)


def print_conditions():
    if DEBUG_PRINT: print conditions_parsed

    location = conditions_parsed['current_observation']['display_location']['full']
    temp_f = conditions_parsed['current_observation']['temp_f']
    print "Current temperature in %s is: %s" % (location, temp_f)


def print_forecast():
    if DEBUG_PRINT: print forecast_parsed
    
    for f_day in forecast_parsed['forecast']['txt_forecast']['forecastday']:
       day = f_day['title']
       d_forecast = f_day['fcttext']
       print "Forecast for %s: %s" % (day, d_forecast)


get_wu_data()
print_conditions()
print_forecast()
